using Microsoft.AspNetCore.Mvc;
using ERPBackend.Models;
using ERPBackend.Services;
using System.Collections.Generic;
using System.Threading.Tasks;
using System;

namespace ERPBackend.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class InventoriesController : ControllerBase
    {
        private readonly IInventoryService _inventoryService;

        public InventoriesController(IInventoryService inventoryService)
        {
            _inventoryService = inventoryService;
        }

        // GET: api/Inventories/paged - 分页获取库存
        [HttpGet("paged")]
        public async Task<ActionResult<object>> GetInventoriesPaged(int page = 1, int pageSize = 10)
        {
            var total = await _inventoryService.GetTotalInventoriesAsync();
            var inventories = await _inventoryService.GetInventoriesPagedAsync(page, pageSize);
            return Ok(new { items = inventories, total });
        }

        // GET: api/Inventories - 获取所有库存
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Inventory>>> GetInventories()
        {
            var inventories = await _inventoryService.GetAllInventoriesAsync();
            return Ok(inventories);
        }

        // GET: api/Inventories/5 - 获取单个库存
        [HttpGet("{id}")]
        public async Task<ActionResult<Inventory>> GetInventory(int id)
        {
            var inventory = await _inventoryService.GetInventoryByIdAsync(id);

            if (inventory == null)
            {
                return NotFound();
            }

            return inventory;
        }

        // GET: api/Inventories/material/{materialId}/warehouse/{warehouseId} - 根据物料和仓库获取库存
        [HttpGet("material/{materialId}/warehouse/{warehouseId}")]
        public async Task<ActionResult<Inventory>> GetInventoryByMaterialAndWarehouse(int materialId, int warehouseId)
        {
            var inventory = await _inventoryService.GetInventoryByMaterialAndWarehouseAsync(materialId, warehouseId);

            if (inventory == null)
            {
                return NotFound();
            }

            return inventory;
        }

        // GET: api/Inventories/alerts - 获取库存预警
        [HttpGet("alerts")]
        public async Task<ActionResult<IEnumerable<Inventory>>> GetInventoryAlerts()
        {
            var alerts = await _inventoryService.GetInventoryAlertsAsync();
            return Ok(alerts);
        }

        // GET: api/Inventories/material/{materialId}/warehouse/{warehouseId}/transactions - 获取库存交易记录
        [HttpGet("material/{materialId}/warehouse/{warehouseId}/transactions")]
        public async Task<ActionResult<IEnumerable<InventoryTransaction>>> GetInventoryTransactions(int materialId, int warehouseId)
        {
            var transactions = await _inventoryService.GetInventoryTransactionsAsync(materialId, warehouseId);
            return Ok(transactions);
        }

        // POST: api/Inventories - 创建库存
        [HttpPost]
        public async Task<ActionResult<Inventory>> PostInventory(Inventory inventory)
        {
            try
            {
                var createdInventory = await _inventoryService.CreateInventoryAsync(inventory);
                return CreatedAtAction("GetInventory", new { id = createdInventory.Id }, createdInventory);
            }
            catch (ArgumentException ex)
            {
                return BadRequest(ex.Message);
            }
        }

        // PUT: api/Inventories/5 - 更新库存
        [HttpPut("{id}")]
        public async Task<IActionResult> PutInventory(int id, Inventory inventory)
        {
            if (id != inventory.Id)
            {
                return BadRequest();
            }

            try
            {
                var updated = await _inventoryService.UpdateInventoryAsync(inventory);
                if (!updated)
                {
                    return NotFound();
                }
            }
            catch (ArgumentException ex)
            {
                return BadRequest(ex.Message);
            }

            return NoContent();
        }

        // DELETE: api/Inventories/5 - 删除库存
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteInventory(int id)
        {
            var deleted = await _inventoryService.DeleteInventoryAsync(id);
            if (!deleted)
            {
                return NotFound();
            }

            return NoContent();
        }

        // PATCH: api/Inventories/material/{materialId}/warehouse/{warehouseId}/quantity - 更新库存数量
        [HttpPatch("material/{materialId}/warehouse/{warehouseId}/quantity")]
        public async Task<IActionResult> UpdateInventoryQuantity(int materialId, int warehouseId, [FromBody] UpdateInventoryQuantityRequest request)
        {
            try
            {
                await _inventoryService.UpdateInventoryQuantityAsync(
                    materialId, 
                    warehouseId, 
                    request.Quantity, 
                    request.TransactionType, 
                    request.Remark, 
                    request.OperatorId
                );
                return NoContent();
            }
            catch (ArgumentException ex)
            {
                return BadRequest(ex.Message);
            }
        }
    }

    // 更新库存数量请求模型
    public class UpdateInventoryQuantityRequest
    {
        public decimal Quantity { get; set; }
        public byte TransactionType { get; set; } // 0:采购入库, 1:生产入库, 2:销售出库, 3:其他出库
        public string? Remark { get; set; }
        public int OperatorId { get; set; }
    }
}